using System;

using UnityEngine;

namespace DL.Tools
{
    /// <summary>
    /// 残影实现
    /// </summary>
    public class AfterGhost3D : MonoBehaviour
    {
        protected GameObject[] Clones;
        public float lifeTime = 3f;

        private void Start()
        {
            var renders = GetComponentsInChildren<SkinnedMeshRenderer>();
            Clones = new GameObject[renders.Length];
            for (int i = 0; i < renders.Length; i++)
            {
                var sr = renders[i];
                var go = new GameObject();
                go.AddComponent<MeshRenderer>().material = sr.material;
                Clones[i] = go;
                var mesh = new Mesh();
                sr.BakeMesh(mesh);
                go.AddComponent<MeshFilter>().mesh = mesh;
                go.transform.SetPositionAndRotation(sr.transform.position, sr.transform.rotation);
            }
        }

        private void Update()
        {
            lifeTime -= Time.deltaTime;
            if (lifeTime < 0f)
            {
                Destroy(this);
            }
        }

        private void OnDestroy()
        {
            foreach (var clone in Clones)
            {
                Destroy(clone);
            }

            Clones = null;
        }
    }
}
